﻿using System;
#if NETFX_CORE
using System.Reflection;
using Windows.UI.Xaml.Data;
#else
using System.Globalization;
using System.Windows.Data;
#endif

namespace FreshMeat.Xaml
{
#if !SILVERLIGHT && !NETFX_CORE
   [System.Windows.Markup.MarkupExtensionReturnType(typeof(IValueConverter))]
#endif
#if NETFX_CORE
   public class ToStringExtension : IValueConverter
   {
#else
   public class ToStringExtension : System.Windows.Markup.MarkupExtension, IValueConverter
   {
      static ToStringExtension converter;

      public override object ProvideValue(IServiceProvider serviceProvider)
      {
         return converter ?? (converter = new ToStringExtension());
      }
#endif

#if NETFX_CORE
      public object Convert(object value, Type targetType, object parameter, string culture)
#else
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
#endif
      {
         if (parameter == null)
            return value.ToString();

         var format = parameter.ToString();

#if NETFX_CORE
         var method = value.GetType().GetRuntimeMethod("ToString", new[] { typeof(string) });
#else
         var method = value.GetType().GetMethod("ToString", new[] { typeof(string) });
#endif
         if (method != null)
            return method.Invoke(value, new object[] { format });

         return value.ToString();
      }

#if NETFX_CORE
      public object ConvertBack(object value, Type targetType, object parameter, string culture)
#else
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#endif
      {
         throw new NotImplementedException();
      }
   }
}